<?php
namespace app\logic;


use think\facade\Cache;

class Version extends Base
{
    protected function initialize()
    {
        parent::initialize();
        $this->model = new \app\model\Version();
    }

    /**
     * 获取列表
     * @param array $where
     * @param string $field
     * @return array
     */
    public function getList($where = [], $field = "*")
    {
        $page = $where['page'] ?? 1;
        $limit = $where['limit'] ?? 10;

        // 删除无用参数
        if(isset($where['page'])) unset($where['page']);
        if(isset($where['limit'])) unset($where['limit']);

        $result = $this->model::withSearch(['sid','status'], $where)
            ->with(['software'])
            ->order('id', 'desc')
            ->field($field)
            ->paginate([
                'page'      => $page,
                'list_rows' => $limit
            ]);
        // 设置关联属性
        $result->visible(['software' => ['id', 'name', 'config']]);

        return [config('status.success'), "ok", $result];
    }

    /**
     * 获取单挑数据
     * @param array $where
     * @param string $field
     * @return array
     */
    public function getInfo($where = [], $field = "*")
    {
        $result = $this->model::where($where)
            ->field($field)
            ->find();

        return [config('status.success'), "ok", $result];
    }

    /**
     * 新增
     * @param $param
     * @return array
     */
    public function add($param)
    {
        // 处理上传文件前缀
        $param_ret = $this->handleParam($param);
        // 新增数据
        $result = $this->model::create($param_ret);
        // 清空缓存
        Cache::clear();
        if($result && $result->id) {
            return [config('status.success'), "新增成功"];
        }
        return [config('status.fail'), "新增失败"];
    }

    /**
     * 修改
     * @param $param
     * @return array
     */
    public function edit($param)
    {
        // 处理上传文件前缀
        $param_ret = $this->handleParam($param);
        // 删除 sid 不允许变更
        unset($param_ret['sid']);
        // 更新数据
        $result = $this->model::update($param_ret);
        // 清空缓存
        Cache::clear();
        if($result && $result->id) {
            return [config('status.success'), "修改成功"];
        }
        return [config('status.fail'), "修改失败"];
    }

    /**
     * 删除
     * @param $param
     * @return array
     */
    public function delete($param)
    {
        $result = $this->model::destroy($param);
        // 清空缓存
        Cache::clear();
        if($result) {
            return [config('status.success'), "删除成功"];
        }
        return [config('status.fail'), "删除成功"];
    }

    /**
     * 修改状态
     * @param int $id
     * @return array
     */
    public function setStatus($id = 0)
    {
        $id = intval($id);
        $info = $this->model::where('id', $id)->findOrEmpty();
        if($info->isEmpty()) {
            return [config('status.noData'), "请求修改的信息不存在"];
        }
        $info->status = !$info->status;
        $info->save();
        // 清空缓存
        Cache::clear();
        return [config('status.success'), "状态修改成功"];
    }

    /**
     * 处理数据值内容
     * @param $param
     * @return mixed
     */
    protected function handleParam($param)
    {
        $soft_info = (new Software())->getInfo(['id' => intval($param['sid'])], "id,name,config");
        if(empty($soft_info)) {
            return $param;
        }
        $config_type = [];
        // 调整数据格式, 用于判断设置数据
        foreach($soft_info->config as $config) {
            $config_type[$config['type']][] = $config['enname'];
        }
        foreach($param['config'] as $key => $val) {
            foreach($config_type as $k => $v) {
                if(!in_array($key, $v)) {
                    continue;
                }
                if($k == "file") {
                    // 设置上传文件路径完整 URL 地址
                    $param = $this->setFileUrl($key, $val, $param);
                } elseif($k == "radio") {
                    // 设置 radio 数据类型
                    $param = $this->setDataType($key, $val, $param, "boolean");
                } elseif($k == "textarea") {
                    // 转义 html 标签
                    $param = $this->setDataType($key, $val, $param, "html");
                }
            }
        }

        return $param;
    }

    /**
     * 处理域名格式
     * @param $key
     * @param $val
     * @param $param
     * @return mixed
     */
    protected function setFileUrl($key, $val, $param)
    {
        $file_info = (new Upload())->getInfo(['href' => $val], 'id,type');
        if(!empty($file_info)) {
            if($file_info->type == "local") {
                // 设置本地域名
                $api_url = rtrim(get_config('site', 'api_url'), "/");
                // 没有设置 API 地址则获取当前
                if(empty($api_url)) $api_url = request()->domain();
                // 没有 http 补充
                if(!preg_match("/^(http|https):\/\//", $api_url)) {
                    $api_url = "http://" . $api_url;
                }
                $param['config'][$key] = $api_url . "/" . $param['config'][$key];
            }else if($file_info->type == "alioss") {
                // 设置 OSS 域名
                $oss_config = get_config('upload');
                $oss_domain = rtrim($oss_config['oss_bind_domain'], "/");
                // 拆分组合阿里云默认 url
                if(empty($oss_domain)) {
                    preg_match("/^(http:\/\/|https:\/\/)?(([a-z0-9-]+\.*){1,4})$/i", rtrim($oss_config['oss_endpoint'], "/"), $matches);
                    $oss_domain = $matches[1] . $oss_config['oss_bucket'] .".". $matches[2];
                }
                // 没有 http 补充
                if(!preg_match("/^(http|https):\/\//", $oss_domain)) {
                    $oss_domain = "http://" . $oss_domain;
                }
                $param['config'][$key] = $oss_domain . "/" . $param['config'][$key];
            }
        }

        return $param;
    }

    /**
     * 设置数据类型
     * @param $key
     * @param $val
     * @param $param
     * @param string $typeof
     * @return mixed
     */
    protected function setDataType($key, $val, $param, $typeof = "boolean")
    {
        switch ($typeof) {
            case "boolean":     $param['config'][$key] = boolval($val);             break;
            case "number":      $param['config'][$key] = intval($val);              break;
            case "string":      $param['config'][$key] = strval($val);              break;
            case "html":        $param['config'][$key] = htmlspecialchars($val);    break;
        }

        return $param;
    }

}